package me.seu.demo.thread.pool;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.util.Date;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 手写延迟消息队列
 *
 * @author liangfeihu
 * @since 2020/2/26 15:16
 */
@Slf4j
public class DelayMsgQueue {

    public static void main(String[] args) {
        ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(10,
                new NamedThreadFactory("scheduleThreadPool"),
                new ThreadPoolExecutor.AbortPolicy());
        //从消息中取出延迟时间及相关信息的代码略
        String str = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
        System.out.println(str);
        int delayTime = 5;
        // 延迟delayTime秒后执行业务逻辑
        executorService.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                //具体操作逻辑
                System.out.println(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss") + "-----定时任务延迟5秒执行------");
            }
        }, 2, delayTime, TimeUnit.SECONDS);

        String strEnd = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
        System.out.println(strEnd);
    }

}
